package com.atguigu.spring5.txdemo.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.atguigu.spring5.txdemo.entity.UserDO;

@Repository
public class ZklDaoImpl implements ZklDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public String queryString() {
		String sql = "select username from t_account where id = ?";
		return jdbcTemplate.queryForObject(sql, String.class, "2"); // 基础类型和string类型
	}

	
	public UserDO queryUserDo(String id) {
		String sql = "select * from t_account where id = ?";
//		String sql = "select * from t_account where id = '2'";
//		UserDO queryForObject = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(UserDO.class));//注意BeanPropertyRowMapper的构造
		// 注意BeanPropertyRowMapper的构造
		UserDO queryForObject = jdbcTemplate.queryForObject(sql, new Object[] { id }, new BeanPropertyRowMapper<UserDO>(UserDO.class));
		return queryForObject;
	}

	
	public List<UserDO> queryAll() {
		String sql = "select * from t_account ";
		List<UserDO> userDoList = jdbcTemplate.query(sql, new Object[] {}, new BeanPropertyRowMapper<UserDO>(UserDO.class));// 注意BeanPropertyRowMapper的构造
		return userDoList;
	}

	
	public int add(UserDO user) {
		String sql = "insert into t_account values (?,?,?)";
		Object[] args = new Object[] { user.getId(), user.getUsername(), user.getMoney() };
		int update = jdbcTemplate.update(sql, args);
		return update;
	}

	
	public int update(UserDO user) {
		String sql = "update t_account set username=? where id=?";
		Object[] args = new Object[] { user.getUsername(), user.getId() };
		int update = jdbcTemplate.update(sql, args);
		return update;
	}

	
	public int delete(UserDO user) {
		String sql = "delete from t_account where id=?";
		Object[] args = new Object[] { user.getId() };
		int update = jdbcTemplate.update(sql, args);
		return update;
	}

	
	public int[] batchAdd(List<UserDO> userDoList) {
		String sql = "insert into t_account values(?,?,?)";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for (UserDO userDO : userDoList) {
			Object[] objects = new Object[] {userDO.getId(),userDO.getUsername(),userDO.getMoney()};
			batchArgs.add(objects);
		}
		int[] batchUpdate = jdbcTemplate.batchUpdate(sql, batchArgs);
		return batchUpdate;
	}

	
	public int[] batchDelete() {
		// TODO Auto-generated method stub
		return null;
	}

}
